
package com.code.ape.codeape.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.code.ape.codeape.admin.api.entity.SysUser;
import com.code.ape.codeape.admin.api.feign.RemoteUserService;
import com.code.ape.codeape.common.core.util.R;
import com.code.ape.codeape.common.core.util.RetOps;
import com.code.ape.codeape.common.security.service.CodeapeUser;
import com.code.ape.codeape.common.security.util.SecurityUtils;
import com.code.ape.codeape.device.api.dto.QcLiquidInfoDTO;
import com.code.ape.codeape.device.api.entity.PaperInfo;
import com.code.ape.codeape.device.api.entity.QcLiquidInfo;
import com.code.ape.codeape.device.api.util.DeviceCheckUtil;
import com.code.ape.codeape.device.api.vo.DeviceInfoVO;
import com.code.ape.codeape.device.api.vo.QcLiquidInfoVO;
import com.code.ape.codeape.device.mapper.QcLiquidInfoMapper;
import com.code.ape.codeape.device.service.QcLiquidInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 质控液
 *
 * @author 公众号：码猿技术专栏   版权：不才陈某所署，侵权必究
 * @date 2023-05-27 20:52:30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class QcLiquidInfoServiceImpl extends ServiceImpl<QcLiquidInfoMapper, QcLiquidInfo> implements QcLiquidInfoService {

	private final RemoteUserService remoteUserService;


	@Override
	public Boolean saveQcLiquidInfo(QcLiquidInfoDTO dto) {
		//step1 校验质控液批号
		Assert.isTrue(DeviceCheckUtil.checkQcLiquid(dto.getBatchNum()),"质控液批号不符合规则！");

		// step2 入库
		QcLiquidInfo qcLiquidInfo = new QcLiquidInfo();
		BeanUtil.copyProperties(dto,qcLiquidInfo);
		//填充必要的信息
		CodeapeUser codeapeUser = Objects.requireNonNull(SecurityUtils.getUser());
		qcLiquidInfo.setHosId(codeapeUser.getHosId());
		qcLiquidInfo.setEnterId(codeapeUser.getId());
		int qcLiquidInfoRows = baseMapper.insert(qcLiquidInfo);
		Assert.isTrue(qcLiquidInfoRows==1,"添加失败！");
		return Boolean.TRUE;
	}

	@Override
	public Page<QcLiquidInfoVO> listPage(Page<QcLiquidInfoVO> page, QcLiquidInfoDTO dto) {
		//step1 执行分页查询
		Page<QcLiquidInfoVO> pageVo = baseMapper.selectQcLiquidInfoPage(page, dto);
		//step2 获取入库人姓名
		List<QcLiquidInfoVO> records = pageVo.getRecords();
		//入库人的全部的id
		Set<Long> enterIds = records.stream().filter(Objects::nonNull).map(QcLiquidInfoVO::getEnterId).collect(Collectors.toSet());

		//step3 调用admin服务获取，入库人姓名不是展示必须，即使服务调用失败也不抛出异常，try起来
		if (CollectionUtil.isNotEmpty(enterIds)) {
			List<SysUser> enterList=new ArrayList<>();
			try{
				R<List<SysUser>> resultEnterUser = remoteUserService.listUserInfoByIds(enterIds);
				enterList= RetOps.of(resultEnterUser).getData().orElse(new ArrayList<>());
			}catch (Exception ex){
				log.error("调用用户服务异常，参数：{}，异常信息：{}", JSON.toJSON(enterIds),ex.getLocalizedMessage());
			}

			if (CollectionUtil.isNotEmpty(enterList)){
				Map<Long, SysUser> userMap = enterList.stream().collect(Collectors.groupingBy(SysUser::getUserId, Collectors.collectingAndThen(Collectors.toList(), list -> list.get(0))));
				records.stream().peek(entity-> entity.setEnterName(Optional.ofNullable(userMap.get(entity.getEnterId())).orElse(new SysUser()).getName())).collect(Collectors.toList());
			}
		}
		return pageVo;
	}

	@Override
	public Boolean updateQcLiquidInfo(QcLiquidInfoDTO dto) {
		//step1 校验质控液批号
		Assert.isTrue(DeviceCheckUtil.checkQcLiquid(dto.getBatchNum()),"质控液批号不符合规则");
		//step2 更新
		QcLiquidInfo qcLiquidInfo = new QcLiquidInfo();
		BeanUtil.copyProperties(dto,qcLiquidInfo);
		int liquidRows = baseMapper.updateById(qcLiquidInfo);
		Assert.isTrue(liquidRows==1,"修改失败！");
		return Boolean.TRUE;
	}

	@Override
	public Boolean removeUpdateQcLiquidInfoById(Long id) {
		return null;
	}

    @Override
    public List<QcLiquidInfoVO> getByDeptId(QcLiquidInfoDTO dto) {
		List<QcLiquidInfo> liquidInfos = baseMapper.selectList(Wrappers.<QcLiquidInfo>lambdaQuery()
				.eq(QcLiquidInfo::getDeptId, dto.getDeptId())
				.eq(QcLiquidInfo::getHosId, dto.getHosId())
				.eq(QcLiquidInfo::getSampleType,dto.getSampleType())
				//未失效
				.gt(QcLiquidInfo::getExpiryDate, LocalDateTime.now())
				.in(CollectionUtil.isNotEmpty(dto.getDataAuth()), QcLiquidInfo::getDeptId, dto.getDataAuth()));
		return BeanUtil.copyToList(liquidInfos,QcLiquidInfoVO.class);
	}
}
